package com.edgclub.edg.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.uc.TouchImageView;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.CryptUtil;
import com.edgclub.edg.utils.util.DensityUtils;

import java.io.File;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ImageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ImageFragment extends GzBaseFragment {

    // TODO: Rename and change types of parameters
    private TouchImageView touch_image;
    private GlideUtils glideUtils;
    private boolean isok;
    public ImageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter register_1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ImageFragment.
     */

    PostsAlbum imagepath;
    TextView yt,save;

    String path="";

    private java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#0.00");
    // TODO: Rename and change types and number of parameters
    public static ImageFragment newInstance(PostsAlbum imagepath) {
        ImageFragment fragment = new ImageFragment();
        Bundle args = new Bundle();
        args.putSerializable("image",imagepath);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        glideUtils = new GlideUtils();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_image, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        touch_image= (TouchImageView) getView().findViewById(R.id.touch_image);
        yt= (TextView) getView().findViewById(R.id.yt);
        save= (TextView) getView().findViewById(R.id.save);

        yt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                path=imagepath.getOriUrl();
//                imageLoaderClient.loadBitmapFromGidle(imagepath.getOriUrl(),touch_image);
                new loadImag().execute();
//                yt.setVisibility(View.GONE);
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new SaveFile().execute();
            }
        });
        if (getArguments() != null) {
            imagepath= (PostsAlbum) getArguments().getSerializable("image");
            String imageUrl1=imagepath.getUrl();
            path=imageUrl1;
//            if(imageUrl1.lastIndexOf(GzImageGalleryViewPagerTopicConfirmActivity.tag)!=-register_1)
//                imageUrl1=imageUrl1.substring(0,imageUrl1.lastIndexOf(GzImageGalleryViewPagerTopicConfirmActivity.tag));
            glideUtils.loadBitmapFromGidleFitCenter(getActivity(),imageUrl1,touch_image);
            if("".equals(imagepath.getOriUrl()))
                yt.setVisibility(View.GONE);
            else{
                yt.setVisibility(View.VISIBLE);
                if(imagepath.getSize()==0){
                    yt.setText("查看原图");
                }else{
                    yt.setText("查看原图("+df.format(imagepath.getSize()/1024.0/1024.0+0.01)+"M)");
                }
            }
        }
        touch_image.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
                if(isok) {
                    try {
                        getActivity().finish();
                        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent motionEvent) {
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent motionEvent) {
                return false;
            }
        });
        handler.sendEmptyMessageDelayed(1,800);
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                touch_image.setImageBitmap((Bitmap) msg.obj);
                yt.setVisibility(View.GONE);
            }else if(msg.what == 1){
                isok=true;
            }
        }
    };


    class SaveFile extends AsyncTask<Object, String, String> {
        //后面尖括号内分别是参数（例子里是线程休息时间），进度(publishProgress用到)，返回值 类型
        @Override
        protected void onPreExecute() {
            //第一个执行方法
            showDialog("正在保存...", false);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Object... params) {
            try {	// TODO Auto-generated method stub

//    			FileName=mComPreferenceUtils.get("coach_id", "")+"-"+mComPreferenceUtils.get("coach_truename", "")+"-"+System.currentTimeMillis()+".txt";
                String saveFile = Constant.SAVEIMAGEPATH
                        + CryptUtil.md5(path) + ".jpg";
                Bitmap bmp = glideUtils.loadBitmap(getActivity(),path, DensityUtils.getScreenW(getActivity()),DensityUtils.getScreenH(getActivity()));
                BitmapUtility.saveImage(bmp, saveFile);

                return "1";

            } catch (Exception e) {
                e.printStackTrace();
            }
            return "0";
        }
        @Override
        protected void onPostExecute(String result) {
            //doInBackground返回时触发，换句话说，就是doInBackground执行完后触发
            //这里的result就是上面doInBackground执行后的返回值，所以这里是"执行完毕"
            if("0".equals(result)){
                Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();
                dismissDialog();
            }else if("1".equals(result)){
                String path1=Constant.SAVEIMAGEPATH
                        + CryptUtil.md5(path) + ".jpg";
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(path1));
                intent.setData(uri);
                if (null != getActivity()){
                    getActivity().sendBroadcast(intent);
                }
                Toast.makeText(getActivity(),"保存成功"+path1,Toast.LENGTH_SHORT).show();
                dismissDialog();
            }

            super.onPostExecute(result);
        }
    }

    class loadImag extends AsyncTask<Object, String, String> {
        //后面尖括号内分别是参数（例子里是线程休息时间），进度(publishProgress用到)，返回值 类型
        @Override
        protected void onPreExecute() {
            //第一个执行方法
            showDialog("正在加载...", true);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Object... params) {
            try {	// TODO Auto-generated method stub

//    			FileName=mComPreferenceUtils.get("coach_id", "")+"-"+mComPreferenceUtils.get("coach_truename", "")+"-"+System.currentTimeMillis()+".txt";
                Bitmap bmp = glideUtils.loadBitmap(getActivity(),path, DensityUtils.getScreenW(getActivity()),DensityUtils.getScreenH(getActivity()));
                Message message = Message.obtain();
                message.what = 0;
                message.obj = bmp;
                handler.sendMessage(message);
                return "1";

            } catch (Exception e) {
                e.printStackTrace();
            }
            return "0";
        }
        @Override
        protected void onPostExecute(String result) {
            //doInBackground返回时触发，换句话说，就是doInBackground执行完后触发
            //这里的result就是上面doInBackground执行后的返回值，所以这里是"执行完毕"
            if("0".equals(result)){
                Toast.makeText(getActivity(),"加载失败",Toast.LENGTH_SHORT).show();
                dismissDialog();
            }else if("1".equals(result)){
//                Toast.makeText(getActivity(),"保存成功"+Constant.SAVEIMAGEPATH
//                        + CryptUtil.md5(path) + ".jpg",Toast.LENGTH_SHORT).show();
                dismissDialog();
            }

            super.onPostExecute(result);
        }
    }
}
